package com.hanfengyi.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hanfengyi.feign.RedisFeignClient;
import com.hanfengyi.hrm.AjaxResult;
import com.hanfengyi.hrm.HttpUtil;
import com.hanfengyi.hrm.NativeHttpUtils;
import com.hanfengyi.hrm.VerifyCodeUtils;
import com.hanfengyi.user.dto.SendEMSDTO;
import com.hanfengyi.user.service.IVerifyCodeService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * User: Han
 * Date: 2020/3/2
 * Time: 17:28
 * Description:
 */
@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisFeignClient redisFeignClient;
    @Override
    public String imageCodeGenerate(String imageCodeKey) {
        if(!StringUtils.hasLength(imageCodeKey))
            throw new IllegalArgumentException("验证码的key值不能为空");
        //1. 生成随机验证码
        String randomCode = UUID.randomUUID().toString().substring(0,4);
        //2. 存储在redis中
        redisFeignClient.setex(imageCodeKey, 300, randomCode);
        //3. 使用base64编码图片
        String imageCode = null;
        try {
            imageCode = VerifyCodeUtils.verifyCode(140,45 ,randomCode );
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageCode;
    }

    @Override
    public void sendSmsCode(Map<String, String> map) {
        //1.从map中取出手机号、验证码、以及redis中存放验证码的key值并校验
        String mobile = map.get("mobile");
        String str="^[1](([3][0-9])|([4][5,7,9])|([5][0-9])|([6][6])|([7][3,5,6,7,8])|([8][0-9])|([9][8,9]))[0-9]{8}$";// 验证手机号
        if(!StringUtils.hasLength(mobile)|| !Pattern.compile(str).matcher(mobile).matches())
            throw new RuntimeException("手机号码无效!");

        String imageCodeKey = map.get("imageCodeKey");
        AjaxResult ajaxResult = redisFeignClient.get(imageCodeKey);
        if(!ajaxResult.isSuccess() || ajaxResult.getResultObj()==null)
            throw new RuntimeException("图形验证码已经过期！");

        String codeInRedis = ajaxResult.getResultObj().toString();
        String userInputCode = map.get("imageCode");
        if(!StringUtils.hasLength(userInputCode)|| !userInputCode.equals(codeInRedis))
            throw new RuntimeException("验证码输入错误！");

        String mobileAsKey = "sms:"+mobile;
        AjaxResult sendInfo = redisFeignClient.get(mobileAsKey);
        Date date = new Date();
        String code;
        //如果用户已经发送过短信，做用户发送短信频繁校验
        if(sendInfo.isSuccess() && sendInfo.getResultObj()!=null){
            SendEMSDTO sendEMSDTO = JSONObject.parseObject(sendInfo.getResultObj().toString(), SendEMSDTO.class);
            //用户发送短信时间小于60s
            if(date.getTime()-sendEMSDTO.getSendDate()<60000)
                throw new RuntimeException("发送短信频繁！请稍后再试！");
            //用户再次发送短信，使用之前的验证码
            code = sendEMSDTO.getSendCode();
        }else{
            //4. 用户如果没有发送过短信，生成新的验证码
            code = String.valueOf(new Random().nextInt(999999));
        }
       //6.将发送信息存储到redis中
        SendEMSDTO sendEMSDTO = new SendEMSDTO();
        sendEMSDTO.setSendCode(code);
        sendEMSDTO.setSendDate(date.getTime());
        sendEMSDTO.setPhone(mobile);
        redisFeignClient.setex(mobileAsKey, 1800,JSON.toJSONString(sendEMSDTO));
        //6.发送短信
        Map<String,String> sendSmsMap = new HashedMap();
        sendSmsMap.put("Uid","hanfy");
        sendSmsMap.put("Key", "d41d8cd98f00b204e980");
        sendSmsMap.put("smsMob", mobile);
        String smsText = "【爱购网】用户您好！您的验证码是: "+code+"有效时间30分钟！";
        sendSmsMap.put("smsText",smsText);
        String url = "http://utf8.api.smschinese.cn/";
        System.out.println(smsText);
       //HttpUtil.sendPost(url, sendSmsMap);
    }
}